import CustomerTable from "@/components/CustomerTable";
import DictTag from "@/components/DictTag";
import { CloudDownloadOutlined, DeleteOutlined, EditOutlined, ExclamationCircleFilled, PlusOutlined } from "@ant-design/icons";
import { ActionType, PageContainer, ProColumns } from "@ant-design/pro-components";
import { Button, Card, Col, Divider, Flex, Input, List, Modal, Popconfirm, Row, Space, Typography, message } from "antd";
import React, { useEffect, useRef, useState } from "react";
import TemplateForm, { TemplateFormData } from "./components/TemplateForm";
import TestTemplateForm from "./components/TemplateTest";
import FilterDrawer from "@/components/FilterDrawer";
import { getPageList, remove } from "@/services/api/module/message/messageTemplate";
import { getDict } from "@/services/api/module/system/dict";
import { useNavigate } from "react-router-dom";
import { createTableColumns, pagination } from "./constants";
import { Panel, PanelGroup, PanelResizeHandle } from "react-resizable-panels";
import CategaryList from "./components/CategaryList";
import ImportExportDropdown from "@/components/ImportExportDropdown";
import HiddenWrapper from "@/components/HiddenWrapper";
const { confirm } = Modal;
import { dict } from "@/utils/DictionaryCacheManager";

const MessageTemplate: React.FC = () => {
	const navigate = useNavigate();
	const [formOpen, setFormOpen] = useState<boolean>(false);
	const [testOpen, setTestOpen] = useState<boolean>(false);
	const actionRef = useRef<ActionType>();
	const tableDiv = useRef<any>();
	const [currentId, setCurrentId] = useState<number | undefined>(undefined);
	const [selectedRows, setSelectedRows] = useState<API.System.MessageTemplateVo[]>([]);
	const [statusOptions, setStatusOptions] = useState<any>([]);
	const [templateModeOptions, setTemplateModeOptions] = useState<any>([]);
	const [configType, setConfigType] = useState<any>([]);
	const [categaryId, setCategaryId] = useState<number | undefined>(undefined);
	useEffect(() => {
		dict.getDict("sys_normal_disable").then(data => {
			setStatusOptions(data);
		});
		dict.getDict("sys_message_config_type").then(data => {
			setConfigType(data);
		});
		dict.getDict("sys_message_template_mode").then(data => {
			setTemplateModeOptions(data);
		});
	}, []);

	const handleColumnEditor = (record: API.System.MessageTemplateVo) => {};
	const handleColumnRemove = (record: API.System.MessageTemplateVo) => {
		handleRemove(record.id as number);
	};
	const handleColumnTest = (record: API.System.MessageTemplateVo) => {};
	const columns = createTableColumns(
		templateModeOptions,
		statusOptions,
		handleColumnEditor,
		handleColumnRemove,
		handleColumnTest
	);
	// 删除
	const handleRemove = async (ids: number | Array<number>) => {
		return new Promise((reslove, reject) => {
			remove(ids)
				.then((res: any) => {
					message.success(res.msg);
					if (actionRef.current) {
						actionRef.current.reload();
					}
					reslove(true);
				})
				.catch(() => {
					reject(true);
				});
		});
	};
	// 删除警告提示
	const showRemoveConfirm = (ids: any, names: any) => {
		confirm({
			title: "警告",
			icon: <ExclamationCircleFilled />,
			content: `您是否确定要永久删除模板名称为“${names}”的模板？删除后，此操作将无法撤销。`,
			onOk() {
				return handleRemove(ids);
			},
			onCancel() {}
		});
	};

	// 关闭表单刷新列表
	const handleTableForm = async () => {
		setFormOpen(false);
		setCurrentId(undefined);
		actionRef?.current?.reload();
	};

	// // 保存
	// const handleSave = async (values: CategaryFormData) => {
	// 	return new Promise((resolve, reject) => {
	// 		categary
	// 			.save({ ...values } as CategaryFormData)
	// 			.then((res: any) => {
	// 				message.success(res.msg);
	// 				handleTableForm();
	// 				resolve(true);
	// 			})
	// 			.catch(() => {
	// 				reject(false);
	// 			});
	// 	});
	// };
	// // 編輯
	// const handleUpdate = async (values: CategaryFormData) => {
	// 	return new Promise((resolve, reject) => {
	// 		categary
	// 			.update({ ...values } as CategaryFormData)
	// 			.then((res: any) => {
	// 				message.success(res.msg);
	// 				handleTableForm();
	// 				resolve(true);
	// 			})
	// 			.catch(() => {
	// 				reject(false);
	// 			});
	// 	});
	// };
	const [searchFormValue, setSearchFormValue] = useState<any>(undefined);
	const [searchValue, setSearchValue] = useState<any>(undefined);
	//数据请求
	const tableDataRequest = async (params: {} | undefined) => {
		return await getPageList({ ...searchFormValue, ...searchValue, categaryId: categaryId }).then((data: any) => {
			return data;
		});
	};
	const handleOnSearch = async (value: any) => {
		setSearchValue({
			userName: value
		});
		actionRef.current?.reload();
	};
	return (
		<>
			<PanelGroup direction="horizontal">
				<Panel defaultSize={20} minSize={0}>
					<CategaryList
						onSelect={(id: number | undefined) => {
							setCategaryId(id);
							actionRef.current?.reload();
						}}
					/>
				</Panel>
				<PanelResizeHandle style={{ width: 7 }} />
				<Panel minSize={75}>
					<CustomerTable<API.System.MessageTemplateVo>
						actionRef={actionRef}
						rowKey="id"
						tableStyle={{ minHeight: "calc(100vh - 220px)" }}
						key="templateCategary"
						toolbar={{
							search: (
								<Space>
									<Input.Search placeholder="通过用户账号搜索" allowClear style={{ width: 280 }} onSearch={handleOnSearch} />
									<FilterDrawer
										columns={columns}
										tableActionRef={actionRef}
										onReset={() => {
											setSearchFormValue(undefined);
											actionRef?.current?.reload();
										}}
										onSubmit={(values: any) => {
											setSearchFormValue(values);
											actionRef?.current?.reload();
										}}
									/>
								</Space>
							)
						}}
						search={false}
						pagination={pagination}
						request={tableDataRequest}
						toolBarRender={() => [
							<Button
								type="primary"
								key="add"
								onClick={async () => {
									navigate("/app/system/message/template/form");
								}}
							>
								<PlusOutlined /> 新增模板
							</Button>,
							// <Button
							// 	type="primary"
							// 	key="export"
							// 	ghost
							// 	onClick={async () => {
							// 		// const tableContent = ReactDOM?.findDOMNode(actionRef.current);
							// 		console.log(actionRef?.current);
							// 	}}
							// >
							// 	<CloudDownloadOutlined /> 导出分类
							// </Button>,
							<ImportExportDropdown
								key="oper"
								columns={columns}
								onExport={() => {
									return Promise.resolve();
								}}
							/>,
							<HiddenWrapper key="remove" hidden={selectedRows?.length !== 0}>
								<Button
									ghost
									type="primary"
									danger
									onClick={() => {
										showRemoveConfirm(
											Array.from(selectedRows, ({ id }) => id),
											Array.from(selectedRows, ({ name }) => name)
										);
									}}
								>
									<DeleteOutlined />
									批量删除
								</Button>
							</HiddenWrapper>
						]}
						columns={columns}
						rowSelection={{
							onChange: (_, selectedRows) => {
								setSelectedRows(selectedRows);
							}
						}}
						tableAlertRender={false}
					/>
				</Panel>
			</PanelGroup>

			{/* <TemplateForm
				open={formOpen}
				onCancel={() => {}}
				categaryOptions={categaryOptions}
				onSubmit={(values: TemplateFormData) => {}}
				id={undefined}
			/> */}
			<TestTemplateForm
				onCancel={() => {
					setCurrentId(undefined);
					setTestOpen(false);
				}}
				onSubmit={function (values: TemplateFormData): any {}}
				id={currentId}
				open={testOpen}
			/>
		</>
	);
};

export default MessageTemplate;
